﻿using Autofac;
using DongFangGuoKai.TaskPlatform.Commn.IOCTag;
using DongFangGuoKai.TaskPlatform.Config;
using DongFangGuoKai.TaskPlatform.WebApi.Utility.Selector;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyModel;
using Quartz;
using System.Reflection;
using System.Runtime.Loader;

namespace DongFangGuoKai.TaskPlatform.WebApi.Utility
{
    public class ApiModule : Autofac.Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            
            var libs = DependencyContext.Default.CompileLibraries
                 .Where(x => !x.Serviceable && x.Type == "project").ToList();
            List<Assembly> assemblies = new();
            foreach (var lib in libs)
            {
                assemblies.Add(AssemblyLoadContext.Default.LoadFromAssemblyName(new AssemblyName(lib.Name)));
            }

            //作用域
            builder.RegisterAssemblyTypes(assemblies.ToArray())
            .Where(t => t.IsAssignableTo<IScoepdTag>() && !t.IsAbstract)
            .AsSelf().AsImplementedInterfaces()
            .InstancePerLifetimeScope()
            .PropertiesAutowired();

            //单例
            builder.RegisterAssemblyTypes(assemblies.ToArray())
          .Where(t => t.IsAssignableTo<ISingtonTag>() && !t.IsAbstract)
          .AsSelf().AsImplementedInterfaces()
          .SingleInstance()
          .PropertiesAutowired();

            //瞬时
            builder.RegisterAssemblyTypes(assemblies.ToArray())
          .Where(t => t.IsAssignableTo<ITransientTag>() && !t.IsAbstract)
          .AsSelf().AsImplementedInterfaces()
          .PropertiesAutowired();


            //Job
            builder.RegisterAssemblyTypes(assemblies.ToArray())
            .Where(t => t.IsAssignableTo<IJob>() && !t.IsAbstract)
            .AsSelf().AsImplementedInterfaces()
            .PropertiesAutowired();


            builder.RegisterType<SchedulerCenter>().SingleInstance().PropertiesAutowired();
            //注册ControllerBase
            Type[] controllersTypeAssembly = typeof(Program).Assembly.GetExportedTypes()
            .Where(type => typeof(ControllerBase).IsAssignableFrom(type)).ToArray();
            builder.RegisterTypes(controllersTypeAssembly).PropertiesAutowired(new AutowiredPropertySelector());

        }
    }
}
